package com.handmark.pulltorefresh.library.refresh;

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Size;
import android.util.SizeF;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.handmark.pulltorefresh.library.R;

public abstract class RotateRefreshLoadingLayout extends RefreshLoadingLayout {

    protected Matrix mRotateMatrix = new Matrix();
    private ViewGroup mRefreshContainer;
    private float mCenterX;
    private float mCenterY;
    private float mScale;


    public RotateRefreshLoadingLayout(Context context) {
        super(context);
        initLayout(context);
    }

    public RotateRefreshLoadingLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLayout(context);
    }

    public RotateRefreshLoadingLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initLayout(context);
    }

    protected void initLayout(Context context) {
        View.inflate(context, R.layout.layout_rotate_refresh_base, this);
        mRefreshContainer = (ViewGroup) findViewById(R.id.rotate_refresh_base_container);
        createCustomizedView(context, mRefreshContainer);
    }

    protected void setRefreshContainerPosition(boolean isHeader) {
        FrameLayout.LayoutParams params = (LayoutParams) mRefreshContainer.getLayoutParams();
        if (isHeader) {
            params.gravity = Gravity.BOTTOM;
        } else {
            params.gravity = Gravity.TOP;
        }

        mRefreshContainer.setLayoutParams(params);
    }

    protected abstract void createCustomizedView(Context context, ViewGroup container);

    protected abstract void onRotateMatrixUpdated();

    protected abstract Point getRotateZoneSize();

    protected abstract float calcScale(Point rotateZoneSize);


    @Override
    public void pullToRefresh() {
        Point rotateZoneSize = getRotateZoneSize();
        mCenterX = rotateZoneSize.x / 2.0f;
        mCenterY = rotateZoneSize.y / 2.0f;
        mScale = calcScale(rotateZoneSize);
    }

    @Override
    public void reset() {
        mRotateMatrix.reset();
        mRotateMatrix.setScale(mScale, mScale);
        onRotateMatrixUpdated();
    }

    @Override
    public void onPull(float scale) {
        float angle = scale * 90f;
        mRotateMatrix.setRotate(angle, mCenterX, mCenterY);
        mRotateMatrix.postScale(mScale, mScale);
        onRotateMatrixUpdated();
    }

    @Override
    public int getContentSize() {
        return mRefreshContainer.getHeight();
    }

    @Override
    public void releaseToRefresh() {
    }

    @Override
    public void hideAllViews() {
    }

    @Override
    public void showInvisibleViews() {
    }
}
